import { Button, Dialog, DialogActions, DialogTitle } from '@mui/material'
import { useMutation } from '@tanstack/react-query'
import { LogOut } from 'lucide-react'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
import { toast } from 'sonner'

import { AUTH_PAGES } from '@/config/pages-url.config'

import { authService } from '@/services/auth.service'

export function Logout() {
	const { push } = useRouter()
	const [open, setOpen] = useState(false)

	const { mutate } = useMutation({
		mutationKey: ['auth/logout'],
		mutationFn: () => authService.logout(),
		onSuccess: () => {
			toast.success('Произведен выход из системы')
			push(AUTH_PAGES.LOGIN)
		},
		onError: error => {
			toast.error(`Ошибка: ${error.message}`)
			console.error(error)
		}
	})

	const handleClickOpen = () => {
		setOpen(true)
	}

	const handleClose = () => {
		setOpen(false)
	}

	const handleConfirm = () => {
		setOpen(false)
		mutate()
	}

	return (
		<>
			<Button
				onClick={handleClickOpen}
				color={'error'}
			>
				<LogOut />
			</Button>
			<Dialog
				open={open}
				keepMounted
				onClose={handleClose}
				aria-describedby='logout-dialog-slide-description'
			>
				<DialogTitle>{'Вы уверены, что хотите выйти?'}</DialogTitle>
				<DialogActions>
					<Button
						color={'error'}
						onClick={handleClose}
						autoFocus
					>
						Нет
					</Button>
					<Button onClick={handleConfirm}>Да</Button>
				</DialogActions>
			</Dialog>
		</>
	)
}
